package com.example.demo1101.demo4;



import com.example.demo3.Ticket;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestTicket02_Lock {
    private static String[] arr = new String[2];
    private static int index = 0;
    private static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Lock lock1 = new ReentrantLock();

        Thread t1 = new Thread(new Ticket() {
            @Override
            public void run() {
                lock1.lock();
                if (arr[index] == null) {
                    arr[index] = "野猪佩奇";
                    index++;
                }
                lock1.unlock();
            }

        });
        Thread t2 = new Thread(new Ticket() {
            @Override
            public void run() {
// synchronized (lock) {
                lock1.lock();
                if (arr[index] == null) {
                    arr[index] = "野猪乔治";
                    index++;
                }
                lock1.unlock();
//     }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(Arrays.toString(arr));

    }
}



